
from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from config import config
import time
import json
import os
from PIL import Image
from selenium.webdriver.chrome.service import Service
#启动新浏览器并返回driver对象并自动登录账号
def create_new_driver():
    # Chrome浏览器

        # 替换这里的路径为您的 ChromeDriver 的实际路径
        chrome_driver_path = r'C:\Program Files\Google\Chrome\chromedriver-win64\chromedriver-win64\chromedriver.exe'  # Windows 系统
        
        # 设置 ChromeDriver 路径
        
        service = Service(executable_path=chrome_driver_path)
        # 不自动关闭浏览器
        option: wd.ChromeOptions = wd.ChromeOptions()
        option.add_experimental_option("detach", True)
        driver = wd.Chrome(service=service, options=option)
        #option.set_headless()
        #driver = wd.Chrome(chrome_options=chrome_options)
        print_with_timestamp("配置浏览器")
        driver.implicitly_wait(10)
        #driver = wd.Chrome(chrome_options=option)
        print_with_timestamp("配置浏览器成功")
        time_delay = 1
        driver.get('http://bsdts.chinaetc.org/sso/app/oauth/login?client_id=000033&response_type=code&redirect_uri=http://bsdts.chinaetc.org/cbms/app/common/oauth/login&scope=USERINFO&state=state&isTop=false&announceCount=0')
        driver.implicitly_wait(60)
        driver.maximize_window()
        time.sleep(1)
        login_with_user(driver)
        return driver
        
def save_image_to_path(binary_data, output_path):
    # 检查路径是否存在，如果不存在则创建路径
    os.makedirs(output_path, exist_ok=True)

    # 保存图像文件
    image = Image.open(binary_data)
    image.save(output_path, "PNG")


def deduplicate_list_by_key(lst,key):
    unique_ids = set()

    # 新建一个空列表，用于存放去重后的结果
    deduplicated_list = []

    for item in lst:
        # 获取元素的 "id" 值
        item_id = item[key]

        # 检查该 "id" 是否已经存在于集合中（去重步骤）
        if item_id not in unique_ids:
            deduplicated_list.append(item)
            unique_ids.add(item_id)

    return deduplicated_list

from datetime import datetime

def print_with_timestamp(*args, **kwargs):
    
    
    if config.is_console :
    #return
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(timestamp, *args, **kwargs)


def save_to_json(data,file_name):
    current_time = datetime.now()
    # 构造文件名
    file_name = file_name + current_time.strftime("%Y-%m-%d_%H-%M-%S") + ".json"
    path = "C:/Users/Administrator/Desktop/导出的数据/"
    apath = path + file_name
    with open(apath, 'w', encoding='utf-8') as file:
        json.dump(data,file, ensure_ascii=False)

def login_with_user(driver):
    driver.find_element(By.XPATH,"//*[@id='mobile']").send_keys(config.user_name)

    driver.find_element(By.XPATH,"//*[@id='passwd']").send_keys(config.password)
    time.sleep(config.delay_time)
    driver.find_element(By.XPATH,"//*[@id='submitButton']").click()
    #userInput = input("登录成功之后输入1,回车继续")
    print("登陆成功")
    time.sleep(config.delay_time)

def getTimeStamp():
     return time.time()